<template>
  <div class="file-list-container">
    <!-- 筛选区域 -->
    <div class="filter-container">
      <el-select v-model="filter.type" placeholder="按文件类型筛选" clearable @change="handleFilter">
        <el-option label="CSV" value="csv"></el-option>
        <el-option label="TSV" value="tsv"></el-option>
        <el-option label="XLSX" value="xlsx"></el-option>
        <el-option label="FASTQ" value="fastq"></el-option>
      </el-select>
      <el-button @click="resetFilter" style="margin-left: 10px;">重置筛选</el-button>
    </div>

    <!-- 文件表格 -->
    <el-table :data="pagedData" style="width: 100%" v-loading="loading" @sort-change="handleSortChange">
      <el-table-column prop="name" label="文件名称" sortable="custom">
        <template #default="scope">
          <el-link type="primary" @click="showVersionHistory(scope.row)">{{ scope.row.name }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="文件类型" width="120"></el-table-column>
      <el-table-column prop="size" label="文件大小" width="150" sortable="custom">
        <template #default="scope">{{ formatSize(scope.row.size) }}</template>
      </el-table-column>
      <el-table-column prop="uploadTime" label="上传时间" width="200" sortable="custom"></el-table-column>
      <el-table-column prop="workflow" label="关联工作流" width="180">
         <template #default="scope">
          <el-select v-model="scope.row.workflow" placeholder="关联工作流" size="small" @change="val => handleWorkflowLink(scope.row, val)">
            <el-option v-for="wf in availableWorkflows" :key="wf.id" :label="wf.name" :value="wf.id"></el-option>
             <el-option label="取消关联" value=""></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="240" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="previewFile(scope.row)">预览</el-button>
          <el-button size="small" type="primary" @click="downloadFile(scope.row)">下载</el-button>
          <el-button size="small" type="danger" @click="deleteFile(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      class="pagination-container"
      :current-page="pagination.currentPage"
      :page-size="pagination.pageSize"
      :total="filteredFiles.length"
      @current-change="handlePageChange"
      layout="total, prev, pager, next"
    ></el-pagination>

    <!-- 文件预览弹窗 -->
    <CommonModal :visible="previewVisible" title="文件预览" @close="previewVisible = false">
        <div v-if="currentFile">
            <p><strong>共 {{previewData.rows}} 行 {{previewData.cols}} 列</strong></p>
            <el-table :data="previewData.data" height="400" border>
                <el-table-column v-for="col in previewData.headers" :key="col" :prop="col" :label="col"></el-table-column>
            </el-table>
        </div>
    </CommonModal>
    
    <!-- 文件版本历史弹窗 -->
    <FileVersion :visible="versionVisible" :file="currentFile" @close="versionVisible = false" />
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import CommonModal from '../common/CommonModal.vue';
import FileVersion from './FileVersion.vue';

const loading = ref(false);
const allFiles = ref([]);
const filteredFiles = ref([]);
const filter = ref({ type: '' });
const pagination = ref({ currentPage: 1, pageSize: 10 });
const previewVisible = ref(false);
const versionVisible = ref(false);
const currentFile = ref(null);
const previewData = ref({ headers: [], data: [], rows: 0, cols: 0 });
const availableWorkflows = ref([]); // 假设从store或API获取

// Mock数据
const mockFiles = [ 
  { id: 1, name: 'gene_expression.csv', type: 'csv', size: 1024 * 1024 * 2.5, uploadTime: '2023-10-01 10:30:00', workflow: 'wf-1' },
  { id: 2, name: 'patient_info.xlsx', type: 'xlsx', size: 1024 * 500, uploadTime: '2023-10-02 14:00:00', workflow: null },
  { id: 3, name: 'sample_reads.fastq', type: 'fastq', size: 1024 * 1024 * 50, uploadTime: '2023-10-03 09:00:00', workflow: 'wf-2' },
];

const mockWorkflows = [
  { id: 'wf-1', name: '单细胞分析流程' },
  { id: 'wf-2', name: '免疫组库分析流程' },
];

// 添加一个方法用于添加新文件
const addFile = (file) => {
  // 为新文件生成唯一ID和当前时间
  const newFile = {
    id: Date.now(), // 使用时间戳作为唯一ID
    name: file.name,
    type: file.name.split('.').pop().toLowerCase(),
    size: file.size,
    uploadTime: new Date().toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }),
    workflow: null
  };
  
  // 将新文件添加到列表开头
  allFiles.value.unshift(newFile);
  handleFilter(); // 重新应用筛选器
};

const fetchFiles = () => {
  loading.value = true;
  setTimeout(() => {
    allFiles.value = mockFiles;
    availableWorkflows.value = mockWorkflows;
    handleFilter();
    loading.value = false;
  }, 500);
};

onMounted(fetchFiles);

const pagedData = computed(() => {
  const start = (pagination.value.currentPage - 1) * pagination.value.pageSize;
  const end = start + pagination.value.pageSize;
  return filteredFiles.value.slice(start, end);
});

const formatSize = (size) => {
  if (size > 1024 * 1024) return `${(size / (1024 * 1024)).toFixed(2)} MB`;
  return `${(size / 1024).toFixed(2)} KB`;
};

const handleFilter = () => {
  pagination.value.currentPage = 1;
  let tempFiles = [...allFiles.value];
  if (filter.value.type) {
    tempFiles = tempFiles.filter(f => f.type === filter.value.type);
  }
  filteredFiles.value = tempFiles;
};

const resetFilter = () => {
  filter.value.type = '';
  handleFilter();
};

const handleSortChange = ({ prop, order }) => {
    const sortOrder = order === 'ascending' ? 1 : -1;
    filteredFiles.value.sort((a, b) => {
        if (a[prop] < b[prop]) return -1 * sortOrder;
        if (a[prop] > b[prop]) return 1 * sortOrder;
        return 0;
    });
};

const handlePageChange = (page) => {
  pagination.value.currentPage = page;
};

const previewFile = (file) => {
  currentFile.value = file;
  // 模拟获取预览数据
  if(file.type === 'csv' || file.type === 'xlsx') {
      previewData.value = {
          headers: ['Gene', 'Sample1', 'Sample2', 'Sample3'],
          data: Array(10).fill(0).map((_, i) => ({ Gene: `Gene${i+1}`, Sample1: Math.random().toFixed(3), Sample2: Math.random().toFixed(3), Sample3: Math.random().toFixed(3) })),
          rows: 1000,
          cols: 4
      };
  } else {
      previewData.value = { headers: [], data: [], rows: 0, cols: 0 }; // FASTQ等不支持表格预览
  }
  previewVisible.value = true;
};

const downloadFile = (file) => {
  ElMessage.success(`开始下载文件: ${file.name}`);
};

const deleteFile = (file) => {
  ElMessageBox.confirm(`确定删除文件 "${file.name}" 吗？删除后不可恢复。`, '警告', {
    confirmButtonText: '确定删除',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    allFiles.value = allFiles.value.filter(f => f.id !== file.id);
    handleFilter();
    ElMessage.success('文件已删除');
  });
};

const showVersionHistory = (file) => {
    currentFile.value = file;
    versionVisible.value = true;
};

const handleWorkflowLink = (file, workflowId) => {
    const linkedFile = allFiles.value.find(f => f.id === file.id);
    if(linkedFile) {
        linkedFile.workflow = workflowId;
        const wf = availableWorkflows.value.find(w => w.id === workflowId);
        if(wf) {
            ElMessage.success(`文件 "${file.name}" 已关联到工作流 "${wf.name}"`);
        } else {
            ElMessage.info(`文件 "${file.name}" 已取消关联`);
        }
    }
};

// 暴露给父组件
defineExpose({ fetchFiles, addFile });
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
